﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Markup;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using VAdvantage.Controls.ToolBarControl;

namespace VAdvantage.Controls
{
    [ContentProperty("ToolBarItems")]
    public partial class ToolBar : UserControl
    {
        public ToolBar()
        {
            InitializeComponent();
            m_ToolBarItemsCache = new List<ToolBarItem>();
            this.ToolBarItems = new ToolBarItemCollection();
            LeftArrow.Click += (o, e) => { PageIndex--; };
            RightArrow.Click += (o, e) => { PageIndex++; };
            this.ToolBarItems.CollectionChanged += OnToolBarItemsCollectionChanged;
        }

        #region Constant Members
        private const double MinToolNarItemWidth = 40;
        private const double DefaultToolBarItemWidth = 40;
        #endregion

        #region DependencyProperty Members

        public static readonly DependencyProperty ToolBarItemsProperty = DependencyProperty.Register("ToolBarItems",
           typeof(ToolBarItemCollection), typeof(ToolBar), new PropertyMetadata(null));
        private static readonly DependencyProperty PageIndexProperty = DependencyProperty.Register("PageIndex",
           typeof(int), typeof(ToolBar), new PropertyMetadata(-1, new PropertyChangedCallback(OnPageIndexPropertyChanged)));
        private static readonly DependencyProperty PageCountProperty = DependencyProperty.Register("PageCount",
            typeof(int), typeof(ToolBar), new PropertyMetadata(1, new PropertyChangedCallback(OnPageCountPropertyChanged)));

        #endregion

        #region Property Members

        private int PageIndex
        {
            get { return (int)GetValue(PageIndexProperty); }
            set { SetValue(PageIndexProperty, value); }
        }

        private int PageCount
        {
            get { return (int)GetValue(PageCountProperty); }
            set { SetValue(PageCountProperty, value); }
        }

        public ToolBarItemCollection ToolBarItems
        {
            get { return (ToolBarItemCollection)GetValue(ToolBarItemsProperty); }
            private set { SetValue(ToolBarItemsProperty, value); }
        }


        #endregion

        #region PropetyChanged

        void OnToolBarItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e == null)
                throw new ArgumentNullException("e");
            if (e.NewItems != null &&  ToolBarContainer != null && e.OldItems !=null)
                foreach (ToolBarItem item in e.OldItems)
                {
                    m_ToolBarItemsCache.Remove(item);
                    ToolBarContainer.Children.Remove(item as UIElement);
                }
            if (e.NewItems != null && ToolBarContainer != null)
                foreach (ToolBarItem item in e.NewItems)
                {
                    m_ToolBarItemsCache.Add(item);
                    ToolBarContainer.Children.Add(item as UIElement);
                }
        }


        private void OnPageIndexPropertyChanged(int oldValue, int newValue)
        {
            if (newValue < 0)
                throw new ArgumentOutOfRangeException("PageIndex less than zero");
            //if (!MultiPage && newValue != 0)
            //    throw new InvalidOperationException("PageIndex should be zero");
            int itemsPerPage = (int)Math.Floor(_ToolBarContainerWidth / DefaultToolBarItemWidth);
            int pageCount = PageCount;
            if (newValue > pageCount - 1)
                throw new ArgumentOutOfRangeException("PageIndex too large");
            if (LeftArrow != null)
            {
                LeftArrow.IsEnabled = newValue != 0;
                LeftArrow.Visibility = LeftArrow.IsEnabled ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
            if (RightArrow != null)
            {
                RightArrow.IsEnabled = newValue != pageCount - 1;
                RightArrow.Visibility = RightArrow.IsEnabled ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
            if (ToolBarContainer != null)
            {
                ToolBarContainer.Children.Clear();
                int start = newValue * itemsPerPage;
                int end = Math.Min((newValue + 1) * itemsPerPage, m_ToolBarItemsCache.Count);
                for (int i = start; i < end; i++)
                    ToolBarContainer.Children.Add(m_ToolBarItemsCache[i] as UIElement );
            }
        }
        private void OnPageCountPropertyChanged(int oldValue, int newValue)
        {
            if (newValue < 1)
                throw new ArgumentOutOfRangeException("PageCount less than one");
            if (RightArrow != null)
            {
                RightArrow.IsEnabled = newValue != PageIndex;
                RightArrow.Visibility = RightArrow.IsEnabled ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
        }
        #endregion

        #region Fields
        private List<ToolBarItem> m_ToolBarItemsCache;
        private double _ToolBarContainerWidth;

        #endregion

        #region Logic Members

        private bool _ForceRequested = false;
        private void OnToolBarContainerSizeChanged(object sender, SizeChangedEventArgs e)
        {
            _ToolBarContainerWidth = e.NewSize.Width;
            //   if (_ForceRequested)
            // {
            _ForceRequested = false;
            // OnToolBarItemsChanged();
            //}
            if (ToolBarContainer != null && m_ToolBarItemsCache.Count != 0)
                OnToolBarItemsChanged();
        }

        private void ResizeToolBarItems()
        {
            int count = ToolBarContainer.Children.Count;
            if (count != 0)
            {
                var width = (ToolBarContainer.Children[0] as FrameworkElement).ActualWidth;
                double current = _ToolBarContainerWidth / count;
                if (current >= DefaultToolBarItemWidth)
                    current = DefaultToolBarItemWidth;
                foreach (FrameworkElement element in ToolBarContainer.Children)
                {
                    element.Width = current;
                }
            }
        }

        private void OnToolBarItemsChanged()
        {
            if (_ToolBarContainerWidth <= 0)
            {
                _ForceRequested = true;
                return;
            }
            double preview = _ToolBarContainerWidth / m_ToolBarItemsCache.Count;
            //MultiPage = preview < MinToolBarWidth;
            //if (!MultiPage)
            //    ResizeFooterItems();
            //else
            //{
            int itemsPerPage = (int)Math.Floor(_ToolBarContainerWidth / DefaultToolBarItemWidth);
            int count = (int)Math.Floor((double)m_ToolBarItemsCache.Count / itemsPerPage);
            PageCount = itemsPerPage * count == m_ToolBarItemsCache.Count ? count : count + 1;
            PageIndex = PageCount - 1;
            //}
        }

        #endregion

        #region PropertyChanged
        private static void OnPageIndexPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((ToolBar)d).OnPageIndexPropertyChanged((int)e.OldValue, (int)e.NewValue);
        }
        private static void OnPageCountPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((ToolBar)d).OnPageCountPropertyChanged((int)e.OldValue, (int)e.NewValue);
        }

        #endregion
    
    }
}

